﻿using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;

namespace IsoCompte.Classe
{
    public class NHibernateHelper
    {
        private static ISessionFactory _sessionFactory;

        private static ISessionFactory SessionFactory
        {
            get
            {
                Log.Logger.Info("Debut Get SessionFactory");
                if (_sessionFactory == null)
                {
                    Log.Logger.Debug("_sessionFactory est null");
                    InitializeSessionFactory();
                }
                Log.Logger.Info("Fin Get SessionFactory");
                return _sessionFactory;
            }
        }

        private static void InitializeSessionFactory()
        {
            // TODO: Paramétrer le choix de la base de données
            // TODO: Comment gérer les ModifBase entre les versions ?
            Log.Logger.Debug("Debut InitializeSessionFactory");
            _sessionFactory = Fluently.Configure()
                .Database(MsSqlCeConfiguration.Standard
                              .ConnectionString(
                                  @"Data Source=C:\Temp\IsoCompte.sdf")
                              //.ShowSql()
                )
                .Mappings(m =>
                          m.FluentMappings
                              .AddFromAssemblyOf<Utilisateur>())
                .ExposeConfiguration(cfg => new SchemaExport(cfg)
                                                .Create(true, true))
                .BuildSessionFactory();
            Log.Logger.Debug("Fin InitializeSessionFactory");
        }
 
        public static ISession OpenSession()
        {
            Log.Logger.Debug("Debut OpenSession");
            Log.Logger.Debug("Fin OpenSession");
            return SessionFactory.OpenSession();
        }

    }
}
